package sf.dsl.example;

import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLContext;
import sf.database.jdbc.sql.SQLParameter;
import sf.spring.util.CollectionUtils;
import sf.tools.StringUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 操作类型的操作
 * 示例1：and exist (select 1 from ... where ....)
 * 示例2：and not exist (select ... from ... where ....)
 */
public class OperatorCondition implements ICondition {
    //操作符，例如 exist, not exist
    private String opt;
    private Example query;

    public OperatorCondition(String opt, Example query) {
        this.opt = opt;
        this.query = query;
    }

    @Override
    public void toSql(StringBuilder sb, List<SQLParameter> list, AtomicBoolean mustTableAlias, DBDialect dialect) {
        String subQuery = "";
        query.dialect = dialect;
        SQLContext sqlContext = ExampleSQL.getSelectSQLContext(query, null, SelectOpt.all, true);
        subQuery = sqlContext.getSql();
        if (CollectionUtils.isNotEmpty(sqlContext.getParas())) {
            list.addAll(sqlContext.getParas());
        }
        if (StringUtils.isNotBlank(subQuery)) {
            if (StringUtils.isNotBlank(opt)) {
                sb.append(opt);
            }
            sb.append("(").append(subQuery).append(")");
        }
    }

    public String getOpt() {
        return opt;
    }

    public void setOpt(String opt) {
        this.opt = opt;
    }

    public Example getQuery() {
        return query;
    }

    public void setQuery(Example query) {
        this.query = query;
    }
}
